const {verify} = require('../util/jwt')
const {jwtSceret} = require('../config/config.default')
const { User} = require('../model')
//验证登录是否失效

module.exports = async (req,res,next)=>{
    //从请求头获取token信息 验证是否有效
    let token = req.headers.authorization
    token = token ? token.split('Bearer ')[1] : null

    //无效 401
    if(!token){
        return res.status(401).end()
    }
    
    //有效 把信息挂载到req 继续执行
    try {
        const decodeToken =  await verify(token,jwtSceret)
        req.user = await User.findById(decodeToken.userId)
        next()
    } catch (error) {
        return res.status(401).end()
    }

   
}